//
//  GRAudioDownloader.m
//  GRFMRemotePlayer_Example
//
//  Created by GR on 2018/1/17.
//  Copyright © 2018年 guorui. All rights reserved.
//

#import "GRAudioDownloader.h"
#import "GRRemotePlayerFileManager.h"

@interface GRAudioDownloader()<NSURLSessionDataDelegate>
{
    long long _offset;
    long long _totalSize;
    NSURL *_url;
}
@property (strong, nonatomic) NSURLSession *session;
@property (strong, nonatomic) NSOutputStream *outputStream;
@end

@implementation GRAudioDownloader

- (NSURLSession *)session {
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

- (void)setMineType:(NSString *)mineType
{
    _mineType = mineType;
}

- (void)downloadWithURL:(NSURL *)url offset:(long long)offset
{
    _offset = offset;
    _url = url;
    

    [self cancelAndClean];
    
    
    if (url == nil) {
        return;
    }
    
    if ([GRRemotePlayerFileManager cacheExistsWithURL:url]) {
        return;
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:0];
    [request setValue:[NSString stringWithFormat:@"bytes=%lld-", offset] forHTTPHeaderField:@"Range"];
    NSLog(@"request - %@", [NSString stringWithFormat:@"bytes=%lld-", offset]);
    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request];
    [dataTask resume];
}


- (void)cancelAndClean
{
    [self.session invalidateAndCancel];
    self.session = nil;
    _loadedSize = 0;
    
    // 删除 tmp 缓存
    [GRRemotePlayerFileManager removeTmpWithURL:_url];
}

#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 1. 从  Content-Length 取出来
    // 2. 如果 Content-Range 有, 应该从Content-Range里面获取
    _totalSize = [response.allHeaderFields[@"Content-Length"] longLongValue];
    NSString *contentRangeStr = response.allHeaderFields[@"Content-Range"];
    if (contentRangeStr.length != 0) {
        _totalSize = [[contentRangeStr componentsSeparatedByString:@"/"].lastObject longLongValue];
    }
    
    self.mineType = response.MIMEType;
    
    self.outputStream =  [NSOutputStream outputStreamToFileAtPath:[GRRemotePlayerFileManager tmpPathWithURL:_url] append:YES];
    [self.outputStream open];
    
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    _loadedSize += data.length;
    [self.outputStream write:data.bytes maxLength:data.length];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(downloading)]) {
        [self.delegate downloading];
    }
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    [self.outputStream close];
    
    if (error == nil) {
        // 下载成功
        long long tmpSize = [GRRemotePlayerFileManager tmpSizeWithURL:_url];
        if (_totalSize == tmpSize) {
            [GRRemotePlayerFileManager moveToCacheWithURL:_url];
        }
    }
    else {
        if (error.code == -999) {
            
            NSLog(@"下载取消 - %@", task.originalRequest.allHTTPHeaderFields);
        }
        else {
            NSLog(@"下载失败 - %@", error);
        }
    }
    
}

@end
